import { Injectable } from '@nestjs/common';
import * as tencentcloud from 'tencentcloud-sdk-nodejs';
import { Client } from 'tencentcloud-sdk-nodejs/tencentcloud/services/ses/v20201002/ses_client';
import { SendEmailRequest } from 'tencentcloud-sdk-nodejs/tencentcloud/services/ses/v20201002/ses_models';
import { ConfigService } from '@nestjs/config';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { Email_SendEmail_SeClass } from './assets/email.class';

const CvmClient = tencentcloud.ses.v20201002.Client;
@Injectable()
export class Email_Service {
  private sesClient: Client;
  constructor(private configService: ConfigService) {
    this.sesClient = new CvmClient({
      credential: {
        secretId: this.configService.get<string>('EMAIL_SECRET_ID'),
        secretKey: this.configService.get<string>('EMAIL_SECRET_KEY'),
      },
      region: 'ap-hongkong',
      profile: {
        httpProfile: {
          endpoint: 'ses.tencentcloudapi.com',
        },
      },
    });
  }

  async email_SendEmail(body: Email_SendEmail_SeClass): Promise<string> {
    const req: SendEmailRequest = {
      FromEmailAddress: this.configService.get<string>('EMAIL_FROMEMAILADDRESS'),
      Destination: [body.email],
      Subject: body.subject,
      Template: {
        TemplateID: Number(this.configService.get<number>('EMAIL_TEMPLATEID')),
        TemplateData: JSON.stringify({ verifyCode: body.code, time: 2 }),
      },
    };
    try {
      await this.sesClient.SendEmail(req);
      return 'OK';
    } catch (error) {
      throw new Class_HttpException_Base(error.message);
    }
  }
}
